package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.core.model.User;
import cn.edu.tju.elm.dto.BusinessCreateDTO;
import cn.edu.tju.elm.dto.BusinessResponseDTO;
import cn.edu.tju.elm.mapper.BusinessMapper;
import cn.edu.tju.elm.model.Business;
import cn.edu.tju.core.model.HttpResult;
//import cn.edu.tju.elb.service.BusinessService;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.core.security.PermissionUtils;
import cn.edu.tju.elm.repository.BusinessRepository;
import cn.edu.tju.elm.service.BusinessService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;


@RestController
@RequestMapping("/api/businesses")
@Tag(name="管理店铺", description = "提供对店铺的增删改查功能")
public class BusinessController {
    @Autowired
    private UserService userService;
    @Autowired
    private BusinessRepository businessRepository;

    @Autowired
    private BusinessService businessService;

    @Autowired
    private BusinessMapper businessMapper;

    @Autowired
    private PermissionUtils permissionUtils;

    // 公共访问接口 - 无需认证
    @GetMapping("/public")
    @Operation(summary = "查询所有店铺（公共访问）", description = "无需登录即可查看所有店铺信息")
    public HttpResult<List<BusinessResponseDTO>> getAllBusinessesPublic(){
        try {
            List<Business> businesses = businessService.getAllBusinesses();
            List<BusinessResponseDTO> responseDTOs = businessMapper.businessesToResponseDTOs(businesses);
            return HttpResult.success(responseDTOs);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "查询店铺失败: " + e.getMessage());
        }
    }

    @GetMapping("/public/{id}")
    @Operation(summary = "根据ID查询店铺（公共访问）", description = "无需登录即可查看店铺详情")
    public HttpResult<BusinessResponseDTO> getBusinessByIdPublic(@PathVariable("id") Long id){
        try {
            Optional<Business> business = businessService.getActiveBusinessById(id);
            if (business.isPresent()) {
                BusinessResponseDTO responseDTO = businessMapper.businessToResponseDTO(business.get());
                return HttpResult.success(responseDTO);
            } else {
                return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "店铺不存在");
            }
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "查询店铺失败: " + e.getMessage());
        }
    }

    @GetMapping("/public/search")
    @Operation(summary = "搜索店铺（公共访问）", description = "无需登录即可搜索店铺")
    public HttpResult<List<BusinessResponseDTO>> searchBusinessesPublic(@RequestParam(required = false) String name,
                                                                        @RequestParam(required = false) String address,
                                                                        @RequestParam(required = false) Integer orderTypeId){
        try {
            List<Business> businesses = businessService.searchBusinesses(name, address, orderTypeId);
            List<BusinessResponseDTO> responseDTOs = businessMapper.businessesToResponseDTOs(businesses);
            return HttpResult.success(responseDTOs);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "搜索店铺失败: " + e.getMessage());
        }
    }

    // 需要认证的接口 - 使用@PreAuthorize进行权限控制
    @GetMapping("")
    @PreAuthorize("hasAuthority('ADMIN') or @permissionUtils.canAccessBusinessData(#ownerId)")
    @Operation(summary = "通过ownerId查询店铺", description = "根据ownerId查询所有店铺")
    public HttpResult<List<BusinessResponseDTO>> getBusinesses(@RequestParam("ownerId") Long ownerId){
        try {
            List<Business> businesses = businessService.getBusinessesByOwnerId(ownerId);
            List<BusinessResponseDTO> responseDTOs = businessMapper.businessesToResponseDTOs(businesses);
            return HttpResult.success(responseDTOs);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "查询店铺失败: " + e.getMessage());
        }
    }

    @PostMapping("")
    @PreAuthorize("hasAnyAuthority('ADMIN','USER','BUSINESS')")
    @Operation(summary = "增加店铺", description = "任何用户都可以增加店铺，但需要经过管理员审核")
    public HttpResult<Business> addBusiness(@RequestBody BusinessCreateDTO businessDto){
        try {
            Business business = businessMapper.dtoToBusiness(businessDto);
            User user = userService.getUserWithAuthorities().get();
            LocalDateTime now = LocalDateTime.now();
            business.setCreator(user.getId());
            business.setCreateTime(now);
            business.setUpdater(user.getId());
            business.setUpdateTime(now);
            business.setDeleted(false);
            Business b = businessService.addBusiness(business);
            return HttpResult.success(b);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "添加店铺失败: " + e.getMessage());
        }
    }

    @GetMapping("/{id}")
    @Operation(summary = "通过店铺id查询店铺")
    public HttpResult<BusinessResponseDTO> getBusiness(@PathVariable("id") Long id){
        try {
            Optional<Business> business = businessService.getBusinessById(id);
            if (business.isPresent()) {
                BusinessResponseDTO responseDTO = businessMapper.businessToResponseDTO(business.get());
                return HttpResult.success(responseDTO);
            } else {
                return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "店铺不存在");
            }
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "查询店铺失败: " + e.getMessage());
        }
    }

    @GetMapping("/search")
    @Operation(summary = "根据店铺名称搜索店铺")
    public HttpResult<List<BusinessResponseDTO>> searchBusinessesByName(@RequestParam String name){
        try {
            List<Business> businesses = businessService.getBusinessesByNameContaining(name);
            List<BusinessResponseDTO> responseDTOs = businessMapper.businessesToResponseDTOs(businesses);
            return HttpResult.success(responseDTOs);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "搜索店铺失败: " + e.getMessage());
        }
    }

    @GetMapping("/all")
    @Operation(summary = "查询所有店铺")
    public HttpResult<List<BusinessResponseDTO>> getAllBusinesses(){
        try {
            List<Business> businesses = businessService.getAllBusinesses();
            List<BusinessResponseDTO> responseDTOs = businessMapper.businessesToResponseDTOs(businesses);
            return HttpResult.success(responseDTOs);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "查询所有店铺失败: " + e.getMessage());
        }
    }

    @GetMapping("/by-address")
    @Operation(summary = "根据地址查询店铺")
    public HttpResult<List<BusinessResponseDTO>> getBusinessesByAddress(@RequestParam String address){
        try {
            List<Business> businesses = businessService.getBusinessesByAddressContaining(address);
            List<BusinessResponseDTO> responseDTOs = businessMapper.businessesToResponseDTOs(businesses);
            return HttpResult.success(responseDTOs);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "根据地址查询店铺失败: " + e.getMessage());
        }
    }

    @GetMapping("/by-order-type")
    @Operation(summary = "根据订单类型查询店铺")
    public HttpResult<List<BusinessResponseDTO>> getBusinessesByOrderType(@RequestParam Long orderTypeId){
        try {
            List<Business> businesses = businessService.getBusinessesByOrderTypeId(orderTypeId);
            List<BusinessResponseDTO> responseDTOs = businessMapper.businessesToResponseDTOs(businesses);
            return HttpResult.success(responseDTOs);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "根据订单类型查询店铺失败: " + e.getMessage());
        }
    }

    @PutMapping("/{id}")
    @PreAuthorize("hasAuthority('ADMIN') or (hasAuthority('BUSINESS') and @permissionUtils.canAccessBusinessData(@businessService.getBusinessById(#id).get().getBusinessOwner().getId()))")
    @Operation(summary = "更新店铺信息", description = "只有管理员和商家有权限更新店铺信息")
    public HttpResult<BusinessResponseDTO> updateBusiness(@PathVariable("id") Long id, @RequestBody Business business){
        try {
            User user = userService.getUserWithAuthorities().get();
            
            // 权限检查：管理员可以更新所有店铺，商家只能更新自己的店铺
            Optional<Business> existingBusiness = businessService.getBusinessById(id);
            if (existingBusiness.isPresent() && !permissionUtils.isAdmin() && 
                !permissionUtils.canAccessBusinessData(existingBusiness.get().getBusinessOwner().getId())) {
                return HttpResult.failure(ResultCodeEnum.BAD_REQUEST, "无权限更新该店铺");
            }
            
            business.setId(id);
            business.setUpdater(user.getId());
            business.setUpdateTime(LocalDateTime.now());
            Business updatedBusiness = businessService.updateBusiness(business);
            BusinessResponseDTO responseDTO = businessMapper.businessToResponseDTO(updatedBusiness);
            return HttpResult.success(responseDTO);
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "更新店铺失败: " + e.getMessage());
        }
    }

    @PatchMapping("/{id}")
    @PreAuthorize("hasAuthority('ADMIN') or (hasAuthority('BUSINESS') and @permissionUtils.canAccessBusinessData(@businessService.getBusinessById(#id).get().getBusinessOwner().getId()))")
    @Operation(summary = "部分更新店铺")
    public HttpResult<BusinessResponseDTO> partiallyUpdateBusiness(@PathVariable("id") Long id, @RequestBody Business business){
        try {
            User user = userService.getUserWithAuthorities().get();
            Optional<Business> existingBusiness = businessService.getBusinessById(id);
            if (existingBusiness.isPresent()) {
                Business businessToUpdate = existingBusiness.get();
                
                // 权限检查：管理员可以更新所有店铺，商家只能更新自己的店铺
                if (!permissionUtils.isAdmin() && !permissionUtils.canAccessBusinessData(businessToUpdate.getBusinessOwner().getId())) {
                    return HttpResult.failure(ResultCodeEnum.BAD_REQUEST, "无权限更新该店铺");
                }
                
                // 只更新非空字段
                if (business.getBusinessName() != null) {
                    businessToUpdate.setBusinessName(business.getBusinessName());
                }
                if (business.getBusinessAddress() != null) {
                    businessToUpdate.setBusinessAddress(business.getBusinessAddress());
                }
                if (business.getBusinessExplain() != null) {
                    businessToUpdate.setBusinessExplain(business.getBusinessExplain());
                }
                if (business.getBusinessImg() != null) {
                    businessToUpdate.setBusinessImg(business.getBusinessImg());
                }
                if (business.getOrderTypeId() != null) {
                    businessToUpdate.setOrderTypeId(business.getOrderTypeId());
                }
                if (business.getStartPrice() != null) {
                    businessToUpdate.setStartPrice(business.getStartPrice());
                }
                if (business.getDeliveryPrice() != null) {
                    businessToUpdate.setDeliveryPrice(business.getDeliveryPrice());
                }
                if (business.getRemarks() != null) {
                    businessToUpdate.setRemarks(business.getRemarks());
                }
                if (business.getDeleted() != null) {
                    businessToUpdate.setDeleted(business.getDeleted());
                }
                businessToUpdate.setUpdater(user.getId());
                businessToUpdate.setUpdateTime(LocalDateTime.now());
                Business updatedBusiness = businessService.updateBusiness(businessToUpdate);
                BusinessResponseDTO responseDTO = businessMapper.businessToResponseDTO(updatedBusiness);
                return HttpResult.success(responseDTO);
            } else {
                return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "店铺不存在");
            }
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "部分更新店铺失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    @PreAuthorize("hasAuthority('ADMIN') or (hasAuthority('BUSINESS') and @permissionUtils.canAccessBusinessData(@businessService.getBusinessById(#id).get().getBusinessOwner().getId()))")
    @Operation(summary = "删除店铺")
    public HttpResult<String> deleteBusiness(@PathVariable("id") Long id){
        try {
            // 权限检查：管理员可以删除所有店铺，商家只能删除自己的店铺
            Optional<Business> existingBusiness = businessService.getBusinessById(id);
            if (existingBusiness.isPresent() && !permissionUtils.isAdmin() && 
                !permissionUtils.canAccessBusinessData(existingBusiness.get().getBusinessOwner().getId())) {
                return HttpResult.failure(ResultCodeEnum.BAD_REQUEST, "无权限删除该店铺");
            }
            
            businessService.deleteBusiness(id);
            return HttpResult.success("删除成功");
        } catch (jakarta.persistence.EntityNotFoundException e) {
            return HttpResult.failure(ResultCodeEnum.NOT_FOUND, "店铺不存在");
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "删除店铺失败: " + e.getMessage());
        }
    }

}
